import json

import requests
from PyQt5 import uic
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QProcess
from PyQt5.QtWidgets import QMessageBox

from peopleSelect import PeopleSelect


# Qt 日常训练实现的代码
class Course(PeopleSelect):
    def __init__(self, mainWindow):
        super().__init__(mainWindow.ui.course, mainWindow)
        self.ui.btn_show_standard.setHidden(True)
        self.ui.box_type.currentIndexChanged.connect(self.clearSelected)
        self.ui.btn_detail.clicked.connect(self.showDetails)
        self.ui.btn_start.clicked.connect(self.start_course)
        self.ui.btn_show_standard.clicked.connect(self.show_standard)
        self.process = QProcess()
        self.standard = None
        self.action = None
        self.response = None
        self.emotion = None
        self.psychology = None

    def loadData(self):
        super().loadData()
        self.ui.btn_show_standard.setHidden(True)
        self.removeAllPeople()

    def showDetails(self):
        if self.ui.box_type.currentIndex() == 0:
            ERROR('请选择课程类型')
            return
        elif self.ui.box_type.currentIndex() == 1:
            self.details = uic.loadUi('ui/course_standard.ui')
            self.setDetailWindow()
            self.standard_detail()
        elif self.ui.box_type.currentIndex() == 2:
            self.details = uic.loadUi('ui/course_response.ui')
            self.setDetailWindow()
            self.response_detail()
        elif self.ui.box_type.currentIndex() == 3:
            self.details = uic.loadUi('ui/course_emotion.ui')
            self.setDetailWindow()
            self.emotion_detail()
        elif self.ui.box_type.currentIndex() == 4:
            self.details = uic.loadUi('ui/course_psychology.ui')
            self.setDetailWindow()
            self.psychology_detail()
        else:
            ERROR('请选择课程类型')
            return

    def standard_detail(self):
        response = requests.get(self.mainWindow.url + '/course/standard/data/course?page=1&limit=1000000')
        data = json.loads(response.text)
        self.courses = data['data']
        course_names = ['']
        for course in self.courses:
            course_names.append(course['course_name'])
        self.details.box_course_select.addItems(course_names)
        self.details.box_course_select.currentIndexChanged.connect(self.standard_course_change)
        self.details.box_action_select.currentIndexChanged.connect(self.standard_action_change)
        self.details.btn_submit.clicked.connect(self.standard_submit)
        self.details.exec_()

    def standard_course_change(self):
        select = self.details.box_course_select.currentIndex()
        self.details.box_action_select.clear()
        if select <= 0:
            self.details.label_course_name.setText('')
            self.details.label_course_description.setText('')
            return

        course_id = self.courses[select - 1]['course_id']
        self.details.label_course_name.setText(self.courses[select - 1]['course_name'])
        self.details.label_course_description.setText(self.courses[select - 1]['course_description'])

        data = json.loads(requests.get(self.mainWindow.url + '/course/standard/data/action/' + str(course_id)).text)
        self.actions = data['data']
        action_names = ['']
        for action in self.actions:
            action_names.append(action['action_name'])
        self.details.box_action_select.addItems(action_names)

    def standard_action_change(self):
        select = self.details.box_action_select.currentIndex()
        if select <= 0:
            self.details.label_action_name.setText('')
            self.details.label_action_description.setText('')
            return
        self.details.label_action_name.setText(self.actions[select - 1]['action_name'])
        self.details.label_action_description.setText(self.actions[select - 1]['action_description'])

    def standard_submit(self):
        if self.details.box_course_select.currentIndex() <= 0 or self.details.box_action_select.currentIndex() <= 0:
            return
        self.standard = self.courses[self.details.box_course_select.currentIndex() - 1]
        self.action = self.actions[self.details.box_action_select.currentIndex() - 1]
        self.response = None
        self.psychology = None
        self.emotion = None
        self.ui.btn_show_standard.setHidden(False)
        self.ui.textBrowser.append(u"已选择训练")
        self.ui.textBrowser.append(u'类型：动作标准训练')
        self.ui.textBrowser.append(u'课程名称：' + self.standard['course_name'])
        self.ui.textBrowser.append(u'动作名称：' + self.action['action_name'])
        self.ui.textBrowser.append(u'')
        self.details.close()

    def response_detail(self):
        response = requests.get(self.mainWindow.url + '/course/actionresponse/data?page=1&limit=1000000')
        data = json.loads(response.text)
        self.courses = data['data']
        course_names = ['']
        for course in self.courses:
            course_names.append(course['course_name'])
        self.details.box_course_select.addItems(course_names)
        self.details.box_course_select.currentIndexChanged.connect(self.response_course_change)
        self.details.btn_submit.clicked.connect(self.response_submit)
        self.details.exec_()

    def response_course_change(self):
        select = self.details.box_course_select.currentIndex()
        if select <= 0:
            self.details.label_course_name.setText('')
            self.details.label_course_description.setText('')
            return
        self.details.label_course_name.setText(self.courses[select - 1]['course_name'])
        self.details.label_course_description.setText(self.courses[select - 1]['course_description'])

    def response_submit(self):
        if self.details.box_course_select.currentIndex() <= 0:
            return
        self.response = self.courses[self.details.box_course_select.currentIndex() - 1]
        self.standard = None
        self.action = None
        self.psychology = None
        self.emotion = None
        self.ui.textBrowser.append(u"已选择训练")
        self.ui.textBrowser.append(u'类型：动作反应训练')
        self.ui.textBrowser.append(u'课程名称：' + self.response['course_name'])
        self.ui.textBrowser.append(u'')
        self.details.close()

    def emotion_detail(self):
        response = requests.get(self.mainWindow.url + '/course/emotion/data?page=1&limit=1000000')
        data = json.loads(response.text)
        self.courses = data['data']
        course_names = ['']
        for course in self.courses:
            course_names.append(course['course_name'])
        self.details.box_course_select.addItems(course_names)
        self.details.box_course_select.currentIndexChanged.connect(self.emotion_course_change)
        self.details.btn_submit.clicked.connect(self.emotion_submit)
        self.details.exec_()

    def emotion_course_change(self):
        select = self.details.box_course_select.currentIndex()
        if select <= 0:
            self.details.label_course_name.setText('')
            self.details.label_course_details.setText('')
            self.details.label_course_type.setText('')
            self.details.label_criminal_gender.setText('')
            self.details.label_criminal_type.setText('')
            self.details.label_criminal_age.setText('')
            self.details.label_criminal_tend.setText('')
            self.details.label_criminal_emotion.setText('')
            self.details.label_criminal_mind.setText('')
            return
        self.details.label_course_name.setText(self.courses[select - 1]['course_name'])
        self.details.label_course_details.setText(self.courses[select - 1]['course_details'])
        self.details.label_course_type.setText(self.courses[select - 1]['course_type'])
        self.details.label_criminal_gender.setText(self.courses[select - 1]['person_gender'])
        self.details.label_criminal_type.setText(self.courses[select - 1]['person_crime_types'])
        self.details.label_criminal_age.setText(self.courses[select - 1]['person_age'])
        self.details.label_criminal_tend.setText(self.courses[select - 1]['person_tend'])
        self.details.label_criminal_emotion.setText(self.courses[select - 1]['person_emotion'])
        self.details.label_criminal_mind.setText(self.courses[select - 1]['person_emotion'])

    def emotion_submit(self):
        if self.details.box_course_select.currentIndex() <= 0:
            return
        self.emotion = self.courses[self.details.box_course_select.currentIndex() - 1]
        self.standard = None
        self.action = None
        self.psychology = None
        self.response = None
        self.ui.textBrowser.append(u"已选择训练")
        self.ui.textBrowser.append(u'类型：情绪训练')
        self.ui.textBrowser.append(u'课程名称：' + self.emotion['course_name'])
        self.ui.textBrowser.append(u'')
        self.details.close()

    def psychology_detail(self):
        response = requests.get(self.mainWindow.url + '/course/psychology/data?page=1&limit=1000000')
        data = json.loads(response.text)
        self.courses = data['data']
        course_names = ['']
        for course in self.courses:
            course_names.append(course['course_name'])
        self.details.box_course_select.addItems(course_names)
        self.details.box_course_select.currentIndexChanged.connect(self.psychology_course_change)
        self.details.btn_submit.clicked.connect(self.psychology_submit)
        self.details.exec_()

    def psychology_course_change(self):
        select = self.details.box_course_select.currentIndex()
        if select <= 0:
            self.details.label_course_name.setText('')
            self.details.label_course_details.setText('')
            self.details.label_course_type.setText('')
            self.details.label_criminal_gender.setText('')
            self.details.label_criminal_type.setText('')
            self.details.label_criminal_age.setText('')
            self.details.label_criminal_tend.setText('')
            self.details.label_criminal_emotion.setText('')
            self.details.label_criminal_mind.setText('')
            return
        self.details.label_course_name.setText(self.courses[select - 1]['course_name'])
        self.details.label_course_details.setText(self.courses[select - 1]['course_details'])
        self.details.label_course_type.setText(self.courses[select - 1]['course_type'])
        self.details.label_criminal_gender.setText(self.courses[select - 1]['person_gender'])
        self.details.label_criminal_type.setText(self.courses[select - 1]['person_crime_types'])
        self.details.label_criminal_age.setText(self.courses[select - 1]['person_age'])
        self.details.label_criminal_tend.setText(self.courses[select - 1]['person_tend'])
        self.details.label_criminal_emotion.setText(self.courses[select - 1]['person_emotion'])
        self.details.label_criminal_mind.setText(self.courses[select - 1]['person_emotion'])

    def psychology_submit(self):
        if self.details.box_course_select.currentIndex() <= 0:
            return
        self.psychology = self.courses[self.details.box_course_select.currentIndex() - 1]
        self.standard = None
        self.action = None
        self.emotion = None
        self.response = None
        self.ui.textBrowser.append(u"已选择训练")
        self.ui.textBrowser.append(u'类型：心理训练')
        self.ui.textBrowser.append(u'课程名称：' + self.psychology['course_name'])
        self.ui.textBrowser.append(u'')
        self.details.close()

    def setDetailWindow(self):
        self.details.setWindowFlags(Qt.SplashScreen | Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint)
        if self.mainWindow.isWhite:
            self.details.setStyleSheet("QDialog {background-color: rgb(255, 255, 255);}")
            self.details.frame.setStyleSheet("QFrame {background-color: rgb(245, 245, 245);}\n"
                                             "QLabel {\n"
                                             "    color: black;\n"
                                             "}\n"
                                             "\n"
                                             "QLineEdit {\n"
                                             "    border-radius: 5px;\n"
                                             "    border: 1px solid rgb(210, 210, 210);\n"
                                             "    color: black;\n"
                                             "    background-color: rgb(255, 255, 255);\n"
                                             "    padding-left: 10px;\n"
                                             "}\n"
                                             "QLineEdit:hover {\n"
                                             "    border: 1px solid rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QLineEdit:focus {\n"
                                             "    border: 1px solid rgb(91, 101, 124);\n"
                                             "}\n"
                                             "/* LINE EDIT */\n"
                                             "QSpinBox {\n"
                                             "    border-radius: 5px;\n"
                                             "    border: 1px solid rgb(210, 210, 210);\n"
                                             "    color: black;\n"
                                             "    background-color: rgb(255, 255, 255);\n"
                                             "    padding-left: 10px;\n"
                                             "}\n"
                                             "QSpinBox:hover {\n"
                                             "    border: 1px solid rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QSpinBox:focus {\n"
                                             "    border: 1px solid rgb(91, 101, 124);\n"
                                             "}\n"
                                             "\n"
                                             "/* RADIO BUTTON */\n"
                                             "QRadioButton{\n"
                                             "    color: rgb(0,0,0);\n"
                                             "}\n"
                                             "QRadioButton::indicator {\n"
                                             "    border: 3px solid rgb(210,210,210);\n"
                                             "    width: 15px;\n"
                                             "    height: 15px;\n"
                                             "    border-radius: 10px;\n"
                                             "    background: rgb(230,230,230);\n"
                                             "}\n"
                                             "QRadioButton::indicator:hover {\n"
                                             "    border: 3px solid  rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QRadioButton::indicator:checked {\n"
                                             "    background: 3px solid rgb(85, 170, 255);\n"
                                             "    border: 3px solid rgb(200,200,200);    \n"
                                             "}\n"
                                             "\n"
                                             "/* COMBOBOX */\n"
                                             "QComboBox{\n"
                                             "	background-color: rgb(255,255,255);\n"
                                             "	border-radius: 5px;\n"
                                             "	border: 2px solid rgb(190,190,190);\n"
                                             "	color:rgb(0,0,0);\n"
                                             "	padding: 5px;\n"
                                             "	padding-left: 10px;\n"
                                             "}\n"
                                             "QComboBox:hover{\n"
                                             "	border: 2px solid rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QComboBox::drop-down {\n"
                                             "	subcontrol-origin: padding;\n"
                                             "	subcontrol-position: top right;\n"
                                             "	width: 25px;\n"
                                             "	border-left-width: 0px;\n"
                                             "	border-left-color: rgba(39, 44, 54, 150);\n"
                                             "	border-left-style: solid;\n"
                                             "	border-top-right-radius: 3px;\n"
                                             "	border-bottom-right-radius: 3px;\n"
                                             "	background-image: url(:/16x16/icons/16x16/cil-arrow-bottom.png);\n"
                                             "	background-position: center;\n"
                                             "	background-repeat: no-reperat;\n"
                                             " }\n"
                                             "QComboBox QAbstractItemView {\n"
                                             "	color: rgb(85, 170, 255);\n"
                                             "	background-color: rgb(27, 29, 35);\n"
                                             "	padding: 10px;\n"
                                             "	selection-background-color: rgb(210,210,210);\n"
                                             "}\n"
                                             " QTextBrowser {\n"
                                             "	border: 0px;\n"
                                             "	color: rgb(0,0,0);\n"
                                             "}\n"
                                             "QPushButton {\n"
                                             "    border: 2px solid rgb(210, 210, 210);\n"
                                             "    border-radius: 5px;    \n"
                                             "    color:rgb(0,0,0);\n"
                                             "    background-color: rgb(210, 210, 210);\n"
                                             "}\n"
                                             "QPushButton:hover {\n"
                                             "    background-color: rgb(190,190,190);\n"
                                             "    border: 2px solid rgb(180,180,180);\n"
                                             "}\n"
                                             "QPushButton:pressed {    \n"
                                             "    background-color: rgb(200,200,200);\n"
                                             "    border: 2px solid rgb(190,190,190);\n"
                                             "}")
            self.details.btn_cancel.clicked.connect(self.detail_cancel)

    def detail_cancel(self):
        self.details.close()

    def start_course(self):
        ids = self.getSelectedIds()
        if len(ids) < 1:
            ERROR(message=u'请选择警员')
            return
        if len(ids) > 1:
            ERROR(message=u'训练只能选择一位警员！')
            return
        response = json.loads(requests.get(self.mainWindow.url + '/admin/police/getOne/' + ids[0]).text)
        if not response['success']:
            ERROR(response['msg'])
            return
        id = str(response['data']['police']['id'])
        self.process.readyReadStandardOutput.connect(self.handle_stdout)
        self.process.readyReadStandardError.connect(self.handle_stderr)
        if self.standard is not None and self.action is not None:
            # 设置程序的工作目录，使得程序能够通过相对路径找到文件
            self.process.setWorkingDirectory(self.mainWindow.course_standard_path)
            # 启动外部程序，参数是一个列表
            self.process.start(self.mainWindow.course_standard_path + self.mainWindow.course_standard_name,
                               [id, str(self.action['action_id']), str(2)])
            self.process.waitForFinished()
            return
        if self.response is not None:
            # 设置程序的工作目录，使得程序能够通过相对路径找到文件
            self.process.setWorkingDirectory(self.mainWindow.course_response_path)
            # 启动外部程序，参数是一个列表
            self.process.start(self.mainWindow.course_response_path + self.mainWindow.course_response_name,
                               [id, str(self.response['course_id']), str(0)])
            self.process.waitForFinished()
            return
        if self.emotion is not None:
            # 设置程序的工作目录，使得程序能够通过相对路径找到文件
            self.process.setWorkingDirectory(self.mainWindow.course_emotion_path)
            # 启动外部程序，参数是一个列表
            self.process.start(self.mainWindow.course_emotion_path + self.mainWindow.course_emotion_name,
                               [str(self.emotion['course_id']), id])
            self.process.waitForFinished()
            return
        if self.psychology is not None:
            # 设置程序的工作目录，使得程序能够通过相对路径找到文件
            self.process.setWorkingDirectory(self.mainWindow.course_psychology_path)
            # 启动外部程序，参数是一个列表
            self.process.start(self.mainWindow.course_psychology_path + self.mainWindow.course_psychology_name,
                               [id, str(self.psychology['course_id'])])
            self.process.waitForFinished()
            return
        ERROR("请选择训练详细信息")

    # 打印调用的外部程序的stdout信息
    def handle_stdout(self):
        print(self.process.readAllStandardOutput())

    # 打印调用的外部程序的stderr信息
    def handle_stderr(self):
        print(self.process.readAllStandardError())

    def show_standard(self):
        if self.standard is None or self.action is None:
            ERROR(message='请选择动作标准训练及训练动作')
            return
        # 设置程序的工作目录，使得程序能够通过相对路径找到文件
        self.process.setWorkingDirectory(self.mainWindow.course_standard_path)
        # 启动外部程序，参数是一个列表
        self.process.start(self.mainWindow.course_standard_path + self.mainWindow.course_standard_name,
                           ["1", str(self.action['action_id']), str(1)])
        self.process.waitForFinished()

    def clearSelected(self):
        self.ui.btn_show_standard.setHidden(True)
        self.standard = None
        self.action = None
        self.response = None
        self.emotion = None
        self.psychology = None


def ERROR(message):
    msg_box = QMessageBox(QMessageBox.Critical, '错误', message)
    msg_box.exec_()
